package com.kehutong.webchat.action;

import com.kehutong.common.DoveClient;
import com.kehutong.common.entity.Root;
import com.kehutong.common.errcode.ErrorCode;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.webchat.entity.WeChatSetting;
import com.kehutong.webchat.enums.WeChatType;
import com.kehutong.webchat.service.WeChatService;
import com.kehutong.webchat.util.WechatHttpClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 微信相关接口
 * @author: liukunlong
 * @date: 2021-04-21 14:14
 */
@MvcAction
@ReqMapping("/kht-bin/we")
public class WeChatAction {
    static final Logger logger = LoggerFactory.getLogger(WeChatAction.class);
    @Inject
    private WeChatService weChatService;

    @Inject
    private FileUrlConfig fileUrlConfig;

    @Inject
    private WechatHttpClient httpClient;

    @Inject
    private DoveClient doveClient;

    @Inject
    private JdbcSession jdbcSession;

    @ReqMapping("/bill/share")
    public Object shareBillUrl(Token token,String houseNo) throws Exception {

        //兼容手机号分享,11位默认手机号码
        if(houseNo.length() == 11){
            try{
                logger.info("分享查询手机号:--> mobile:{}",houseNo);
                Set<String> mobiles = new HashSet(Arrays.asList(houseNo));
                JSONObject result = doveClient.post("/crm/resident/service/getResidentListByMobiles", http -> {
                    JSONObject body = new JSONObject();
                    body.put("mobiles", mobiles);
                    http.setBody(body.toString());
                });

                JSONArray data = result.getJSONArray("data");
                if (Objects.isEmpty(data)) {
                    return new ArrayList<>();
                }
                for (int i = 0; i < data.size(); i++) {
                    JSONObject json = data.getJSONObject(i);
                    houseNo = json.getString("houseNo");
                    break;
                }
            }catch (Exception ex){
                logger.error("分享查询手机号有问题！houseNo：{}",houseNo);
            }
        }

        JSONObject h = getHouseById(token, houseNo);
        if (h == null) {
            return Result.error(0, "无效的房屋");
        }

        WeChatSetting setting = jdbcSession.findOne(WeChatSetting.class)
                .eq("companyNo", token.getCompanyNo())
                .eq("type", WeChatType.xiaochengxu)
                .eq("deleted", false)
                .exe();
        if(Objects.isNull(setting)){
            setting = jdbcSession.findOne(WeChatSetting.class)
                    .eq("companyNo", Root.ROOT_ID)
                    .eq("type", WeChatType.xiaochengxu)
                    .eq("deleted", false)
                    .exe();
        }
        JSONObject versionResult = doveClient.post("/admin/service/corp/module/version/get", (http) -> {
            JSONObject body = new JSONObject();
            body.put("companyNo",token.getCompanyNo());
            http.setBody(body.toJSONString());
        });
        logger.info("----------------------适配催缴小程序版本:{}",versionResult);
        String payVersion="1.0";
        if (versionResult.getIntValue("code") == 200) {
            JSONObject data=versionResult.getJSONObject("data");
            payVersion=data.getString("payVersion");
        }
        String accessToken = weChatService.getAccessToken(setting.getAppId());

        String finalPayVersion = payVersion;
        String finalHouseNo = houseNo;
        JSONObject result = httpClient.post("/wxa/generate_urllink", http ->{
            http.addParam("access_token", accessToken);

            JSONObject body = new JSONObject();
            StringBuffer buffer = new StringBuffer();
            buffer.append("houseNo=")
                    .append(finalHouseNo)
                    .append("&companyNo=")
                    .append(token.getCompanyNo());

            //根据版本判断适配小程序跳转的路径
            if(Objects.equal(finalPayVersion,"2.0")){
                body.put("path", "/pages/billsv2/list/index");
            }else{
                body.put("path", "/pages/bills/list/index");
            }
            logger.info("跳转小程序路径{}",body.getString("path"));
            //

            body.put("query", buffer.toString());
            body.put("is_expire", true);
            body.put("expire_type", 1);
            body.put("expire_interval", 7);
            http.setBody(body.toJSONString());
        });

        JSONObject r = new JSONObject();
        if(result.getInteger("errcode") == ErrorCode.WORK_OK.code){
            r.put("shareUrl", result.getString("url_link"));
        }

        r.put("title","账单缴费通知");
        r.put("desc","您有账单未交费，请及时处理。");
        r.put("fileId","");

        return r;
    }

    @ReqMapping("/bill/miniprogram")
    public Object miniprogram(Token token,JSONObject jsonObject) throws Exception {
        WeChatSetting setting = jdbcSession.findOne(WeChatSetting.class)
                .eq("companyNo", token.getCompanyNo())
                .eq("type", WeChatType.xiaochengxu)
                .eq("deleted", false)
                .exe();
        if(Objects.isNull(setting)){
            setting = jdbcSession.findOne(WeChatSetting.class)
                    .eq("companyNo", Root.ROOT_ID)
                    .eq("type", WeChatType.xiaochengxu)
                    .eq("deleted", false)
                    .exe();
        }

        String accessToken = weChatService.getAccessToken(setting.getAppId());

        JSONObject result = httpClient.post("/wxa/generate_urllink", http ->{
            http.addParam("access_token", accessToken);

            JSONObject body = new JSONObject();
            StringBuffer buffer = new StringBuffer();
            buffer.append("id=").append(jsonObject.getString("id"));
            buffer.append("&open_id=").append(jsonObject.getString("open_id"));
            buffer.append("&projectId=").append(jsonObject.getString("projectId"));
            buffer.append("&memberid=").append(jsonObject.getString("memberId"));
            body.put("path", "/pages/doorControl/list/index");
            body.put("query", buffer.toString());
            body.put("is_expire", true);
            body.put("expire_type", 1);
            body.put("expire_interval", 7);
            http.setBody(body.toJSONString());
        });

        JSONObject r = new JSONObject();
        if(result.getInteger("errcode") == ErrorCode.WORK_OK.code){
            r.put("page", result.getString("url_link"));
        }
        r.put("appid","wx3f14689148e657a2");
        r.put("title", "访客通行证");
        r.put("imgUrl","");
        return r;
    }

    @ReqMapping("/getwxacode")
    public Object getwxacode(Token token,String appId,String path) throws Exception {
        String accessToken=weChatService.getAccessToken(appId);
        byte[] result = httpClient.getPostToImage("/wxa/getwxacode", http -> {
            http.addParam("access_token",accessToken);
            JSONObject body=new JSONObject();
            body.put("path",path);
            body.put("width",430);
            http.setBody(body.toJSONString());
        });
//        String str = new String(result, "UTF-8");
        final Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(result);

/*        String result = httpClient.postImage("/wxa/getwxacode", http -> {
            http.addParam("access_token",accessToken);
            JSONObject body=new JSONObject();
            body.put("path",path);
            body.put("width",430);
            http.setBody(body.toJSONString());
        });
        final Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(result.getBytes("UTF-8"));*/


       /* String str = new String(result, "UTF-8");
        File file = new File("D:/2.png");
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(result, 0, result.length);
        outputStream.flush();
        System.out.println("result"+result);
        return Result.download(file);*/
//        base64StringToImage1(result);
//
//        final Base64.Encoder encoder = Base64.getEncoder();
//
//        base64StringToImage(encoder.encodeToString(result));
//
//        return encoder.encodeToString(result);
    }

    public JSONObject getHouseById(Token token, String id) throws Exception {
        JSONObject result = doveClient.post("/basic/house/service/get", http->{
            http.addHeader("companyNo", token.getCompanyNo());
            http.addParam("id", id);
        });

        if(Objects.isNull(result)){
            return null;
        }

        JSONObject data = result.getJSONObject("data");

        if (Objects.isNull(data)) {
            return null;
        }

        return data;
    }

    /**
     * 将一个字符串转化为输入流
     *
     * @param sInputString
     * @return
     */
    public static InputStream getStrToStream(String sInputString) {
        if (sInputString != null && !sInputString.trim().equals("")) {
            try {
                ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
                return tInputStringStream;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    static void base64StringToImage(String base64String) throws Exception{
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes1 = decoder.decode(base64String);

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            java.awt.image.BufferedImage bi1 = ImageIO.read(bais);
            File w2 = new File("f://meinv.bmp");//可以是jpg,png格式
            ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片，此处不需改动
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void base64StringToImage1(byte[] bytes1) throws Exception{
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            java.awt.image.BufferedImage bi1 = ImageIO.read(bais);
            File w2 = new File("f://meinv.bmp");//可以是jpg,png格式
            ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片，此处不需改动
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
